use tokio::task;
use reqwest::{Client, Method};
use std::{sync::{atomic::{AtomicUsize, Ordering}, Arc}, time::Duration};
use flume::{Sender, Receiver, bounded};
use futures::stream::{FuturesUnordered, StreamExt};
use std::time::Instant;
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use std::collections::HashMap;

use crate::{config, sender};


// 生成请求并循环放入队列
pub async fn generate_requests(tx: Sender<reqwest::Request>, index: usize) {
    let request = build_request(index);

    // 获取开始时间
    let start = Instant::now();
    // 持续时间
    let duration = Duration::new( config::CONFIG.requests_config[index].duration_seconds, 0); // 设置循环持续时间为 10 秒

    // 创建一个异步循环
    while Instant::now() - start < duration {
        let request = request.try_clone().unwrap();
        if tx.send_async(request).await.is_err() {
            break;
        }
        // println!("Producer {} sent a request", id);
    }
}

fn build_request(index: usize) ->reqwest::Request{
    // 获取请求地址
    let url:String = config::CONFIG.requests_config[index].address.clone();

    // 获取请求方法
    let method: Method = match config::CONFIG.requests_config[index].method.as_str() {
        "GET" => Method::GET,
        "POST" => Method::POST,
        "PUT" => Method::PUT,
        "DELETE" => Method::DELETE,
        "PATCH" => Method::PATCH,
        "HEAD" => Method::HEAD,
        _ => panic!("未知的请求方法"),
    };

    // 创建请求体
    let body = match config::CONFIG.requests_config[index].body.clone() {
        Some(body) => body,
        None => String::new(),
    };

    // 构建请求头
    let header_map = match config::CONFIG.requests_config[index].headers.clone() {
        Some(headers) => map_to_header_map(headers),
        None => HeaderMap::new(),
    };

    let mut builder = reqwest::Client::builder();
    match config::CONFIG.requests_config[index].protocol_version.as_str() {
        "1" => builder = builder.http1_only(),
        "2" => builder = builder.http2_prior_knowledge(),
        _ => builder = builder.http2_prior_knowledge(),
    };
    let client = builder.build().expect("Failed to build client");

    let request = client
        .request(method.clone(), &url) // 克隆请求方法和URL以确保每个请求独立
        .headers(header_map) // 确保每个请求都有自己的头部副本
        .body(body.clone())
        .build()
        .expect("Failed to build request");

    request
}

fn map_to_header_map(headers: HashMap<String, String>) -> HeaderMap {
    let mut header_map = HeaderMap::new();
    for (key, value) in headers {
        // 尝试从字符串创建 HeaderName
        if let Ok(header_name) = HeaderName::from_bytes(key.as_bytes()) {
            // 尝试从字符串创建 HeaderValue
            if let Ok(header_value) = HeaderValue::from_str(&value) {
                // 插入头部到 HeaderMap 中
                header_map.insert(header_name, header_value);
            } else {
                // 处理 HeaderValue 创建失败的情况（值无效）
                println!("无效的头部值: {}", value);
            }
        } else {
            // 处理 HeaderName 创建失败的情况（无效的头部名称）
            println!("无效的头部名称: {}", key);
        }
    }
    header_map
}